package com.db.concurrency.vehicles;

import java.util.*;
import java.util.concurrent.*;

/**
 * PublishingVehicleTracker
 * <p/>
 * Vehicle tracker that safely publishes underlying state
 * 
 * @author Anton Kotov
 */

public class PublishingVehicleTracker {
  private final Map<String, SynchronizedPoint> locations;
  private final Map<String, SynchronizedPoint> unmodifiableMap;

  public PublishingVehicleTracker(Map<String, SynchronizedPoint> locations) {
    this.locations = new ConcurrentHashMap<String, SynchronizedPoint>(locations);
    this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
  }

  public Map<String, SynchronizedPoint> getLocations() {
    return unmodifiableMap;
  }

  public SynchronizedPoint getLocation(String name) {
    SynchronizedPoint loc = locations.get(name);
    if (loc == null)
      throw new IllegalArgumentException("No such ID: " + name);
    return loc;
  }

  public void setLocation(String name, int x, int y) {
    if (!locations.containsKey(name))
      throw new IllegalArgumentException("No such ID: " + name);
    locations.get(name).set(x, y);
  }
}
